<template>
  <div id="houseCost" class="p-2 addListBox">
    <div v-if="routeType == 'add'" style="margin: 20px 10px;font-weight: 600;font-size: 26px;display:flex;align-items: center;">
      添加房屋物业费缴费记录
    </div>
    <div v-else style="margin: 20px 10px;font-weight: 600;font-size: 26px;display:flex;align-items: center;">修改房屋物业费缴费记录</div>
    <el-card shadow="never">
      <el-table v-loading="loading" :data="houseInfoList">
        <el-table-column align="center" width="130px">
          <template #header>
            <div>小区名称 <span style="color: #ff0000;">*</span> <br /></div>
          </template>
          <template #default="scope">
            <el-select
              class="slese"
              @visible-change="communityHandleVisibleChange"
              v-model="scope.row.projectId"
              placeholder="请选择小区"
              ref="selectRef"
              @change="communityChanged($event,scope.row)"
              v-if="routeType == 'add'"
            >
              <el-option class="communityDropdown" v-for="item in communityOptions" :key="item.id" :label="item.projectName" :value="item.id" />
              <p class="el-select-dropdown__empty" v-show="loadingmore">加载中</p>
            </el-select>
            <span v-else> {{scope.row.projectName}} </span>
          </template>
        </el-table-column>

        <el-table-column align="center" width="130px">
          <template #header>
            <div>房屋号 <span style="color: #ff0000;">*</span></div>
          </template>
          <template #default="scope">
            <el-select
              class="slese"
              @visible-change="houseNameHandleVisibleChange($event,scope)"
              @change="getHouseArea(scope.row)"
              v-model="scope.row.houseId"
              placeholder="请选择房屋"
              ref="selectRef"
              filterable
              v-if="routeType == 'add'"
              :filter-method="getHouseHomeList"
            >
              <el-option
                class="houseNametDropdown"
                v-for="item in houseNameList"
                :key="item.houseId"
                :label="item.houseNumber"
                :value="item.houseId"
              />
              <p class="el-select-dropdown__empty" v-show="loadingmore">加载中</p>
            </el-select>
            <span v-else> {{scope.row.houseNumber}} </span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="80px">
          <template #header>
            <div>房屋类别 <span style="color: #ff0000;">*</span> <br /></div>
          </template>
          <template #default="scope">
            <span v-show="scope.row.houseCategory==1">住宅</span>
            <span v-show="scope.row.houseCategory==2">商铺</span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="80px">
          <template #header>
            <div>房屋面积 <span style="color: #ff0000;">*</span></div>
          </template>
          <template #default="scope">
            <span> {{scope.row.houseArea}} </span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="300px">
          <template #header>
            <div>物业费 <span style="color: #ff0000;">*</span></div>
          </template>
          <template #default="scope">
            <div style="display: flex;justify-content:left;width:100%;">
              <el-input
                type="number"
                v-model="scope.row.houseChargeMoney"
                placeholder="单价"
                style="width: 80px"
                @input="changeCost('houseChargeMoney',scope.row)"
              />
              <div style="margin:0 10px;">×</div>
              <el-input v-model="scope.row.houseArea" disabled style="width: 80px" />
              <div style="margin:0 10px;">=</div>
              <el-input
                type="number"
                v-model="scope.row.houseManagementCost"
                placeholder="物业费"
                style="width: 130px"
                @input="changeStandard('houseManagementCost',scope.row)"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" width="300px">
          <template #header>
            <div>装修垃圾清运费</div>
          </template>
          <template #default="scope">
            <div style="display: flex;justify-content:left;width:100%;">
              <el-input
                type="number"
                v-model="scope.row.wasteChargeMoney"
                placeholder="单价"
                style="width: 80px"
                @input="changeCost('wasteChargeMoney',scope.row)"
              />
              <div style="margin:0 10px;">×</div>
              <el-input v-model="scope.row.houseArea" disabled style="width: 80px" />
              <div style="margin:0 10px;">=</div>
              <el-input
                type="number"
                v-model="scope.row.houseWasteCose"
                placeholder="装修垃圾清运费"
                style="width: 130px"
                @input="changeStandard('houseWasteCose',scope.row)"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center">
          <template #header>
            <div>
              是否开具发票 <br />
              <el-switch
                v-model="isNeedInvoiceType"
                class="ml-2"
                inline-prompt
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                active-text="整体一致"
                inactive-text="逐个修改"
              />
            </div>
          </template>
          <template #default="scope">
            <el-select
              class="slese"
              v-model="scope.row.isNeedInvoice"
              placeholder="请选择"
              ref="selectRef"
              @change="isNeedInvoiceChanged($event,scope.row)"
            >
              <el-option v-for="item in is_need_invoice" :key="item.value" :label="item.label" :value="item.value" />
              <p class="el-select-dropdown__empty" v-show="loadingmore">加载中</p>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="缴费日期" align="center" width="160px">
          <template #default="scope">
            <el-date-picker
              clearable
              v-model="scope.row.housePayDate"
              type="date"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择缴费日期"
            ></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column align="center" width="300px">
          <template #header>
            <div>
              物业费周期 <span style="color: #ff0000;">*</span> <br />
              <el-switch
                v-model="timeRangeCWSwitchType"
                class="ml-2"
                inline-prompt
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                active-text="整体一致"
                inactive-text="逐个修改"
              />
            </div>
          </template>
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.houseManagementStartDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择开始日期"
              @change="startTimer(scope.row)"
              style="width:45%;"
            ></el-date-picker>
            <span style="margin: 0 6px;">至</span>
            <el-date-picker
              v-model="scope.row.houseManagementEndDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择结束日期"
              @change="endTimer(scope.row)"
              style="width:45%;"
            ></el-date-picker>
          </template>
        </el-table-column>

        <el-table-column v-if="routeType == 'add'" label="操作" align="center" class-name="small-padding fixed-width" width="50px">
          <template #default="scope">
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="houseInfoList = houseInfoList.filter(item => item != scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div style="display: flex;justify-content: center;margin-top: 20px;">
      <el-button v-if="routeType == 'add'" type="primary" icon="Plus" @click="addLine">追加一条</el-button>
      <el-button v-if="routeType == 'add'" type="success" icon="Position" @click="handleQuery">提交全部</el-button>
      <el-button v-else type="success" icon="Position" @click="handleQuery">提交修改</el-button>
      <el-button @click="goBack">返 回</el-button>
    </div>
  </div>
</template>

<script setup name="AssetCataAdd" lang="ts">
import { listProject } from '@/api/business/project';
import { listHouseInfo } from '@/api/business/houseInfo';
import { getHouseCost, addHouseCost, updateHouseCost } from '@/api/business/houseCost';
import { HouseCostVO } from '@/api/business/houseCost/types';
import { ProjectQuery } from '@/api/business/project/types';
import { listStandard } from '@/api/business/standard';
import { addDays } from 'date-fns';
import { ref } from 'vue'


const communityOptions = ref()

const route = useRoute()
const routeType = ref('add');
const communitySwitchType = ref(true);
const categorySwitchType = ref(true);

const houseInfoList = ref<HouseCostVO[]>([]);
const listItem = {
  houseCostId: undefined,
  projectId: undefined,
  houseId: undefined,
  houseNumber: undefined,
  houseCategory: undefined,
  houseArea: undefined,
  houseManagementCost: undefined,
  houseWasteCose: undefined,
  housePayDate: undefined,
  houseManagementStartDate: undefined,
  houseManagementEndDate: undefined,
  houseCollectionDate: undefined,
  remark: undefined,
  houseChargeMoney: undefined,
  wasteChargeMoney: undefined,
  isNeedInvoice:'0',
}
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { charge_category } = toRefs<any>(proxy?.useDict('charge_category'));
const { is_need_invoice } = toRefs<any>(proxy?.useDict('is_need_invoice'));

const loading = ref(true);
const houseNameQueryParams = ref({
  pageNum: 1,
  pageSize: 10,
  projectId:undefined,
  houseNumber:undefined
})
const communityParams = ref<ProjectQuery>({
  pageNum: 1,
  pageSize: 10,
  isExit: 0
})

const communityTotal = ref(0);
const houseNameTotal = ref(0);

const houseNameList = ref()
const timeRangeCWSwitchType = ref(true);
const isNeedInvoiceType = ref(true);

// 追加一条
const addLine = () => {
  if(houseInfoList.value.length > 0) {
    communitySwitchType.value?listItem.projectId=houseInfoList.value[0].projectId:undefined
    categorySwitchType.value?listItem.houseCategory=houseInfoList.value[0].houseCategory:undefined
    timeRangeCWSwitchType.value?listItem.houseManagementStartDate=houseInfoList.value[0].houseManagementStartDate:undefined
    timeRangeCWSwitchType.value?listItem.houseManagementEndDate=houseInfoList.value[0].houseManagementEndDate:undefined
    isNeedInvoiceType.value?listItem.isNeedInvoice=houseInfoList.value[0].isNeedInvoice:undefined
  }
  houseInfoList.value.push(JSON.parse(JSON.stringify(listItem)))
}

const hasNoEmptyValues = () => {
  let flag = true
  // let checkNum = true
  // let arr = JSON.parse(JSON.stringify(houseInfoList.value)).reduce((result:any, obj:any)=>{
  //   let target = result.find((item:any) => {
  //     return item.propertyAssetLedgerId === obj.propertyAssetLedgerId;
  //   });
  //   if (target) {
  //     target.outboundQuantity = target.outboundQuantity + obj.outboundQuantity
  //   } else {
  //     result.push(obj);
  //   }
  //   return result;
  // }, [])
  for(let i=0;i<houseInfoList.value.length;i++) {
    if(routeType.value == 'edit') {
      if(houseInfoList.value[i].projectId == '' || houseInfoList.value[i].houseId == '' || houseInfoList.value[i].houseManagementStartDate == '' || houseInfoList.value[i].houseManagementEndDate == '' || houseInfoList.value[i].projectId == null || houseInfoList.value[i].houseId == null || houseInfoList.value[i].houseManagementStartDate == null || houseInfoList.value[i].houseManagementEndDate == null){
        // flag?ElMessage.error('请将信息填写完成！'):''
        // flag = false
        ElMessage.error('请将信息填写完成！')
        return false
      }else if(houseInfoList.value[i].houseManagementCost <= 0 || houseInfoList.value[i].houseManagementCost>999999999){
        ElMessage.error('请填写合理的物业费！')
        return false
      }else if(houseInfoList.value[i].houseManagementCost <= 0 || houseInfoList.value[i].houseManagementCost>999999999){
        ElMessage.error('请填写合理的物业费！')
        return false
      }else if(houseInfoList.value[i].houseWasteCose < 0 || houseInfoList.value[i].houseWasteCose>999999999){
        ElMessage.error('请填写合理的装修垃圾清运费！')
        return false
      }
      if (i==houseInfoList.value.length-1) {
        return true
      }
    }else {
      if(houseInfoList.value[i].projectId == '' || houseInfoList.value[i].houseId == '' || houseInfoList.value[i].houseManagementStartDate == '' || houseInfoList.value[i].houseManagementEndDate == '' || houseInfoList.value[i].projectId == null || houseInfoList.value[i].houseId == null || houseInfoList.value[i].houseManagementStartDate == null || houseInfoList.value[i].houseManagementEndDate == null){
        ElMessage.error('请将信息填写完成！')
        return false
      }else if(houseInfoList.value[i].houseManagementCost <= 0 || houseInfoList.value[i].houseManagementCost>999999999){
        ElMessage.error('请填写合理的物业费！')
        return false
      }else if(houseInfoList.value[i].houseWasteCose < 0 || houseInfoList.value[i].houseWasteCose>999999999){
        ElMessage.error('请填写合理的装修垃圾清运费！')
        return false
      }
      if (i==houseInfoList.value.length-1) {
        return true
      }
    }
  }
  return flag
}

// 提交全部
const handleQuery = async () => {
  if(hasNoEmptyValues()) {
    if(routeType.value == 'edit') {
      await updateHouseCost({'houseCostListBo':houseInfoList.value}).then(() =>  {proxy?.$modal.msgSuccess("修改成功");});
      await goBack()
    }else {
      await addHouseCost({'houseCostListBo':houseInfoList.value}).then((res) =>  {
        sessionStorage.setItem('houseCost','')
        proxy?.$modal.msgSuccess("新增成功");
      });
      await goBack()
    }
  }
}

/** 返回 */
const goBack = () =>{
  const obj = { path: "/costManagement/houseCost" };
  proxy?.$tab.closeOpenPage(obj);
}

/** 查询小区管理列表 */
const getList = async () => {
  loading.value = true;
  const community = await listProject(communityParams.value);
  communityOptions.value = community.rows
  communityTotal.value = community.total;
  loading.value = false;
}
const scopeIndex=ref(0)

const communityHandleVisibleChange = (visible: any) => {
  try {
    if (visible) {
      // 如果下拉框显示
      let communityDropdown: any = document.getElementsByClassName('communityDropdown')[0].parentElement.parentElement
      // 监听下拉框滚动事件
      communityDropdown.addEventListener('scroll', communityLoadNextPage)
    } else {
      // 如果下拉框隐藏
      let communityDropdown: any = document.getElementsByClassName('communityDropdown')[0].parentElement.parentElement
      // 移除下拉框滚动事件监听
      communityDropdown.removeEventListener('scroll', communityLoadNextPage)
    }
  } catch (error) {}
}
const houseNameHandleVisibleChange = (visible: any,scope:any) => {
  scopeIndex.value = scope.$index
  try {
    if (visible) {
      // 如果下拉框显示
      let length = (document.getElementsByClassName('houseNametDropdown').length)/houseInfoList.value.length*scopeIndex.value
      let houseNametDropdown : any = document.getElementsByClassName('houseNametDropdown')[length].parentElement.parentElement
      //let houseNametDropdown = document.getElementsByClassName('houseNametDropdown')[0].parentElement.parentElement
      // 监听下拉框滚动事件
      houseNametDropdown.addEventListener('scroll', houseNametLoadNextPage)
    } else {
      // 如果下拉框隐藏
      let length = (document.getElementsByClassName('houseNametDropdown').length)/houseInfoList.value.length*scopeIndex.value
      let houseNametDropdown : any = document.getElementsByClassName('houseNametDropdown')[length].parentElement.parentElement
      //let houseNametDropdown = document.getElementsByClassName('houseNametDropdown')[0].parentElement.parentElement
      // 移除下拉框滚动事件监听
      houseNametDropdown.removeEventListener('scroll', houseNametLoadNextPage)
    }
  } catch (error) {}
}
const loadingmore = ref(false)
const loadingnomore = ref(false)
const communityLoadNextPage = async () => {
  // let communityDropdown: any = document.querySelector('.el-select-dropdown__wrap');
  let communityDropdown: any = document.getElementsByClassName('communityDropdown')[0].parentElement.parentElement;
  // 判断下拉框是否触底
  if (communityDropdown.scrollTop + communityDropdown.clientHeight >= communityDropdown.scrollHeight - 2) {
    loadingnomore.value = false
    loadingmore.value = true
    if (communityOptions.value.length + 1 <= communityTotal.value && loadingmore.value) {
      communityParams.value.pageNum ++
      const res = await listProject(communityParams.value)
      communityOptions.value.length + 1 <= communityTotal.value?communityOptions.value.push(...res.rows):''
      loadingmore.value = false
    }else{
      loadingmore.value = false
      communityDropdown.removeEventListener('scroll', communityLoadNextPage)
      loadingnomore.value = true
    }
  } else {
    loadingnomore.value = true
  }
}
const houseNametLoadNextPage = async () => {
  let length = (document.getElementsByClassName('houseNametDropdown').length)/houseInfoList.value.length*scopeIndex.value
  let houseNametDropdown : any = document.getElementsByClassName('houseNametDropdown')[length].parentElement.parentElement
  // 判断下拉框是否触底
  if (houseNametDropdown.scrollTop + houseNametDropdown.clientHeight >= houseNametDropdown.scrollHeight - 2) {
    loadingnomore.value = false
    loadingmore.value = true
    if (houseNameList.value.length + 1 <= houseNameTotal.value && loadingmore.value) {
      houseNameQueryParams.value.pageNum ++
      const res = await listHouseInfo(houseNameQueryParams.value)
      houseNameList.value.length + 1   <= houseNameTotal.value?houseNameList.value.push(...res.rows):''
      loadingmore.value = false

    }else{
      loadingmore.value = false
      houseNametDropdown.removeEventListener('scroll', houseNametLoadNextPage)
      loadingnomore.value = true
    }
  } else {
    loadingnomore.value = true
  }
}

const communityChanged = async (id:string,row:any)=> {
  communityOptions.value.forEach((element) => {
    if(element.id == id) {
      row.projectId = element.id
      if(communitySwitchType.value) {
        houseInfoList.value.forEach(item => {
          item.projectId = row.projectId
        })
      }
    }
  });
  getHouseList(id)
}

/** 获取房屋信息 */
const getHouseList = async (id?: string | number) => {
  listItem.houseId=undefined
  listItem.houseNumber=undefined
  listItem.houseCategory=undefined
  listItem.houseArea=undefined
  listItem.houseManagementCost=undefined
  listItem.houseWasteCose=undefined
  listItem.houseChargeMoney=undefined
  listItem.wasteChargeMoney=undefined
  houseNameQueryParams.value.projectId = id
  const house = await listHouseInfo(houseNameQueryParams.value);
  houseNameList.value = house.rows
  houseNameTotal.value = house.total
}

const isNeedInvoiceChanged = (id:string,row:any) => {
  if(isNeedInvoiceType.value) {
      houseInfoList.value.forEach(item => {
        item.isNeedInvoice = row.isNeedInvoice
      })
    }
}

const queryParamsSF = ref({
  pageNum: 1,
  pageSize: 10,
  projectId: undefined,
  chargeCategory: undefined
});
/** 获取房屋详细信息 */
const getHouseArea = async (row:any) => {
  if (!row) return
  houseNameList.value.forEach(item => {
    if(item.houseId == row.houseId) {
      row.houseNumber = item.houseNumber
      row.houseCategory = item.houseCategory
      row.houseArea = item.houseArea
    }
  })
  if(row.houseCategory == 1) {
    queryParamsSF.value.chargeCategory = charge_category.value[0].value
    const houseChargeMoney = await listStandard(queryParamsSF.value);
    row.houseChargeMoney = houseChargeMoney.rows[0].chargeMoney
    row.houseManagementCost =parseFloat(( row.houseChargeMoney * row.houseArea).toFixed(2))
  }else {
    queryParamsSF.value.chargeCategory = charge_category.value[2].value
    const houseChargeMoney = await listStandard(queryParamsSF.value);
    row.houseChargeMoney = houseChargeMoney.rows[0].chargeMoney
    row.houseManagementCost =parseFloat(( row.houseChargeMoney * row.houseArea).toFixed(2))
  }
  queryParamsSF.value.chargeCategory = charge_category.value[3].value
  const wasteChargeMoney = await listStandard(queryParamsSF.value);
  row.wasteChargeMoney = wasteChargeMoney.rows[0].chargeMoney
  row.houseWasteCose =parseFloat(( row.wasteChargeMoney * row.houseArea).toFixed(2))
}

const getHouseHomeList = async (value:string) =>{
  if(value){
    houseNameQueryParams.value.houseNumber = value
    const house = await listHouseInfo(houseNameQueryParams.value);
    houseNameList.value = house.rows
    communityTotal.value = house.total
  }
}

/** 修改费用 */
const changeCost = async (type:any,row:any) => {
  if (type == 'houseChargeMoney') {
    row.houseManagementCost = row.houseArea ?  parseFloat((row.houseArea*1 * row.houseChargeMoney).toFixed(2)) : undefined
  } else {
    row.houseWasteCose = row.houseArea ?  parseFloat((row.houseArea*1 * row.wasteChargeMoney).toFixed(2)) : undefined
  }
}

/** 修改标准 */
const changeStandard = async (type:any,row:any) => {
  if (type == 'houseManagementCost') {
    row.houseChargeMoney = row.houseArea ?  (row.houseManagementCost / row.houseArea).toFixed(2) : undefined
  } else {
    row.wasteChargeMoney = row.houseArea ?  (row.houseWasteCose / row.houseArea).toFixed(2) : undefined
  }
}

const startTimer = (row:any) => {
  if (row.houseManagementStartDate) {
    let timer = addDays(row.houseManagementStartDate, 365)
    let date = new Date(timer);
    let y = date.getFullYear();
    let m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    let d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    row.houseManagementEndDate = y + '-' + m + '-' + d + ' 00:00:00'
  } else {
    row.houseManagementEndDate = undefined
  }
  if (timeRangeCWSwitchType.value) {
    houseInfoList.value.forEach(item => {
        item.houseManagementStartDate = row.houseManagementStartDate
        item.houseManagementEndDate = row.houseManagementEndDate
    })
  }
}

const endTimer = (row:any) => {
  let timer = addDays(row.houseManagementEndDate, -365)
  let endDate = new Date(timer);
  let timer1 = addDays(row.houseManagementStartDate, -365)
  let startDate = new Date(timer1);
  if (endDate.getTime() < startDate.getTime()) {
    startTimer(row)
    ElMessage.warning('结束时间不能小于开始时间');
  }
  if (timeRangeCWSwitchType.value) {
    houseInfoList.value.forEach(item => {
        item.houseManagementStartDate = row.houseManagementStartDate
        item.houseManagementEndDate = row.houseManagementEndDate
    })
  }
}


onMounted(async () => {
  console.log(is_need_invoice)
  await getList()
  if(route.query.type == 'edit') {
    routeType.value = route.query.type
    getHouseCost(route.query.id).then(res => {
      houseInfoList.value = [res.data]
      houseInfoList.value.forEach( element => {
        element.houseChargeMoney = element.houseArea && element.houseManagementCost ?  (element.houseManagementCost / element.houseArea).toFixed(2) : undefined
        element.wasteChargeMoney = element.houseArea && element.houseWasteCose ?  (element.houseWasteCose / element.houseArea).toFixed(2) : undefined
      })
    })
  }else{
    addLine()
  }
})
</script>
<style>
.el-table .cell {
  padding: 0 4px;
}
.addListBox .el-date-editor  {
  --el-date-editor-width: 122px;
}
.error-row {
  background:rgba(255, 0, 0, .3) !important;
}
</style>
